package com.webshooter;

import com.webshooter.encoder.Event;
import com.webshooter.encoder.UpdateEntityEvent;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonBuilderFactory;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;

@Startup
@Singleton
public class ClientUpdater {

    private final List<Event> events = Collections.synchronizedList(new ArrayList<Event>());
    @Resource
    TimerService tservice;
    private final long updateInterval = 50;

    @PostConstruct
    public void init() {
        tservice.createIntervalTimer(updateInterval, updateInterval, new TimerConfig());
    }

    public void addEvent(Event event) {
        synchronized (events) {
            if (event instanceof UpdateEntityEvent) {
                List<Event> found = new ArrayList<>();
                UpdateEntityEvent evt = (UpdateEntityEvent) event;
                for (Event iter : events) {
                    if (iter instanceof UpdateEntityEvent) {
                        UpdateEntityEvent it = (UpdateEntityEvent) iter;
                        if (evt.entity.name.equals(it.entity.name)) {
                            found.add(iter);
                        }
                    }
                }
                events.removeAll(found);
            }
            events.add(event);
        }
    }

    @Timeout
    public void timeout() throws InterruptedException {
        if (events.isEmpty()) {
            return;
        }
        JsonBuilderFactory factory = Json.createBuilderFactory(null);
        JsonObjectBuilder objBuilder = factory.createObjectBuilder();
        JsonArrayBuilder arrayBuilder = Json.createArrayBuilder();
        synchronized (events) {
            for (Event event : events) {
                arrayBuilder.add(event.toJson());
            }
            events.clear();
        }
        objBuilder.add("events", arrayBuilder);
        StringWriter sw = new StringWriter();
        JsonWriter jw = Json.createWriter(sw);
        jw.writeObject(objBuilder.build());
        jw.close();
        ShooterEndpoint.sendAll(sw.toString());
    }
}
